<?php

namespace backend\models;


use services\models\CommentsReply;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\CommentsRelation as CommentsRelationModel;
use services\models\MemberScore;

/**
 * CommentsRelation represents the model behind the search form about `common\models\CommentsRelation`.
 */
class CommentsRelation extends CommentsRelationModel
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['goods_id', 'bestry_uid', 'level', 'is_show', 'status', 'create_time'], 'required', 'on'=>'create'],
            [['id', 'comment_id', 'order_id', 'goods_id', 'product_id', 'bestry_uid', 'level', 'is_try', 'is_reply', 'reply_id', 'is_show', 'status', 'flag'], 'integer'],
            [['create_time'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * @inheritdoc
     */



    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = self::find()->joinWith('comments', true , 'inner join')
            ->joinWith('goods_detail', true, 'left join')
            ->joinWith('comments_reply', true, 'left join');//innerJoin('comments c', 'c.comment_id = comments_relation.comment_id')->all();


        if(isset($params['goods_ids'])){
            $query->where(' comments_relation.goods_id  in ('.$params['goods_ids'].')');
        }

       // $query->orderBy('comments_relation.create_time desc');

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination'=>[
                'pageSize'=>20,
            ],
            'sort'=>[
                'defaultOrder'=>[
                    'create_time'=>SORT_DESC
                ]
            ],

        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }


        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'comments_relation.comment_id' => $this->comment_id,
            //'order_id' => $this->order_id,
            'goods_id' => $this->goods_id,
            'product_id' => $this->product_id,
            'bestry_uid' => $this->bestry_uid,
            'level' => $this->level,
            'create_time' => $this->create_time,
            'is_try' => $this->is_try,
            'is_reply' => $this->is_reply,
            'comments_relation.reply_id' => $this->reply_id,
            'is_show' => $this->is_show,
            'status' => $this->status,
            'flag'  => $this->flag,
        ]);

        $this->start_time = !empty($params['CommentsRelation']['start_time'])?$params['CommentsRelation']['start_time']:'';
        $this->end_time = !empty($params['CommentsRelation']['end_time'])?$params['CommentsRelation']['end_time']:'';
        if(!empty($this->start_time)){
            $query->andFilterWhere(['>=', 'comments.create_time', $this->start_time]);
        }
        if(!empty($this->end_time)) {
            $query->andFilterWhere(['<=', 'comments.create_time', $this->end_time]);
        }

        return $dataProvider;
    }

    /*
     * 仅is_show为1，且status为0或1的评论需要写入商品评论redis
     * 全部状态的评论均可写入用户个人评论redis
     * */
    public function updateCommentRedis($comment_id){

        $commentData = CommentsRelation::find()->where([ 'comment_id'=> $comment_id])->asArray()->one();

        \Yii::$app->redis_comments->hmset('comment_' . $comment_id, $commentData);//评论详情


        if($commentData['is_show'] == 1 && in_array($commentData['status'], array(0,1))) {//仅处于展示、通过或精华状态的评论才可以写入商品评论redis

            // 加入商品评论ID列表
            \Yii::$app->redis_comments->zadd(
                'goods_comment_' . $commentData['goods_id'],
                $commentData['status'] . $commentData['create_time'],
                $commentData['comment_id']
            );

            $this->updateGoodAndBad($commentData);//更新好中差评列表
        }
        else{
            //从商品评论ID列表移除
            Yii::$app->redis_comments->zrem('goods_comment_'.$commentData['goods_id'], $commentData['comment_id']);
            //从好评ID表移除
            \Yii::$app->redis_comments->zrem(
                'goods_comment_A_' . $commentData['goods_id'],
                $commentData['comment_id']
            );
            //从中评ID列表移除
            \Yii::$app->redis_comments->zrem(
                'goods_comment_B_' . $commentData['goods_id'],
                $commentData['comment_id']
            );
            //从差评ID列表移除
            \Yii::$app->redis_comments->zrem(
                'goods_comment_C_' . $commentData['goods_id'],
                $commentData['comment_id']
            );
        }

        if($commentData['status'] == 1){//个人中心精华评论
            // 加入用户个人中心精华评论ID列表
            \Yii::$app->redis_comments->zadd(
                'user_comment_perfect_' . $commentData['bestry_uid'],
                $commentData['create_time'],
                $commentData['comment_id']
            );
        }
        else{
            Yii::$app->redis_comments->zrem(
                'user_comment_perfect_' . $commentData['bestry_uid'],
                $commentData['comment_id']);
        }
        if($commentData['is_reply'] == 1) {//有回复评论

            // 加入用户个人中心客户回复评论列表
            \Yii::$app->redis_comments->zadd(
                'user_comment_reply_' . $commentData['bestry_uid'],
                $commentData['create_time'],
                $commentData['comment_id']
            );
        }
        else{
            Yii::$app->redis_comments->zrem('user_comment_reply_' . $commentData['bestry_uid'],
                $commentData['comment_id']);
        }

        // 用户个人中心评论列表写入redis
        \Yii::$app->redis_comments->zadd(
            'user_comment_' . $commentData['bestry_uid'],
            $commentData['create_time'],
            $commentData['comment_id']
        );

        $this->updateFeedbackRate($commentData['goods_id']);//更新好中差评率
        //$this->updateUserCommentNumberToRedis($commentData['bestry_uid']);//更新用户评论条数
    }

    /*
     * 更新redis里的评论详情
     * */
    public function updateCommentDetailRedis($detail){
        Yii::$app->redis_comments->set('comment_content_' . $detail['comment_id'], $detail['content']);
        unset($detail['content']);
        Yii::$app->redis_comments->hmset('comment_' . $detail['comment_id'], $detail);
    }


    /*
     * 更新客服回复评论的redis
     * */
    public function updateReplyRedis($reply_id, $reply_relation){

        $replyData = CommentsReply::find()->where([ 'reply_id'=> $reply_id])->asArray()->one();

        if(!empty($replyData)) {
            // 客服回复评论写入redis
            Yii::$app->redis_comments->hmset('comment_reply_' . $replyData['comment_id'], $replyData);
            Yii::$app->redis_comments->hmset('comment_' . $reply_relation['comment_id'], $reply_relation);
            if($reply_relation['is_reply'] == 1) {//有回复评论

                // 加入用户个人中心客户回复评论列表
                \Yii::$app->redis_comments->zadd(
                    'user_comment_reply_' . $reply_relation['bestry_uid'],
                    $reply_relation['create_time'],
                    $reply_relation['comment_id']
                );
            }
            else{
                Yii::$app->redis_comments->zrem('user_comment_reply_' . $reply_relation['bestry_uid'],
                    $reply_relation['comment_id']);
            }

        }

    }

    /*
     * 更新商品好中差评列表
     * redis写入
     * */
    public function updateGoodAndBad($commentData){

        if(!empty($commentData)){

            if(in_array($commentData['level'],array(4,5))){//4、5星级视为好评
                //加入好评列表
                \Yii::$app->redis_comments->zadd(
                    'goods_comment_A_' . $commentData['goods_id'],
                    $commentData['status'].$commentData['create_time'],
                    $commentData['comment_id']
                );
            }
            else{
                //从好评列表移除
                \Yii::$app->redis_comments->zrem(
                    'goods_comment_A_' . $commentData['goods_id'],
                    $commentData['comment_id']
                );
            }

            if(in_array($commentData['level'], array(2,3))){//2、3星级视为中评

                //加入中评列表
                \Yii::$app->redis_comments->zadd(
                    'goods_comment_B_' . $commentData['goods_id'],
                    $commentData['status'].$commentData['create_time'],
                    $commentData['comment_id']
                );

            }
            else{
                //从中评列表移除
                \Yii::$app->redis_comments->zrem(
                    'goods_comment_B_' . $commentData['goods_id'],
                    $commentData['comment_id']
                );
            }

            if($commentData['level'] == 1){
                //加入差评列表
                \Yii::$app->redis_comments->zadd(
                    'goods_comment_C_' . $commentData['goods_id'],
                    $commentData['status'].$commentData['create_time'],
                    $commentData['comment_id']
                );
            }
            else{
                //从差评列表移除
                \Yii::$app->redis_comments->zrem(
                    'goods_comment_C_' . $commentData['goods_id'],
                    $commentData['comment_id']
                );
            }

        }
    }

    //更新redis里的好中差评率,及对应评论条数
    public function updateFeedbackRate($goods_id){

/*        $all = yii::$app->db->createCommand('SELECT COUNT(*) c FROM `comments_relation`
                                              WHERE `status` in (0,1) AND is_show = 1 AND goods_id = '.$goods_id);
        $allCount = $all->queryOne();*/

        $allCount = CommentsRelation::find()->where(['goods_id'=>$goods_id, 'is_show'=>1])
                                            ->andWhere('status in (0,1)')->count();

        if($allCount == 0){
            $ARate = $BRate = $CRate = 0;
            $ACount = $BCount = $CCount = 0;//评论条数
        }
        else {
/*            $good = yii::$app->db->createCommand('SELECT COUNT(*) c FROM `comments_relation`
                                                    WHERE `status` in (0,1) AND is_show = 1 AND `level` in (4,5) AND goods_id = ' . $goods_id);
            $goodCount = $good->queryOne();*/
            //好评条数
            $ACount = CommentsRelation::find()->where(['goods_id'=>$goods_id, 'is_show'=>1])
                                              ->andWhere('status in (0,1)')
                                              ->andWhere('level in (4,5)')->count();

            $ARate = round(intval($ACount) / intval($allCount) * 100);//好评率

/*            $ok = yii::$app->db->createCommand('SELECT COUNT(*) c FROM `comments_relation`
                                                    WHERE `status` in (0,1) AND is_show = 1 AND `level` in (2,3) AND goods_id = ' . $goods_id);
            $okCount = $ok->queryOne();*/
            //中评条数
            $BCount = CommentsRelation::find()->where(['goods_id'=>$goods_id, 'is_show'=>1])
                                            ->andWhere('status in (0,1)')
                                            ->andWhere('level in (2,3)')->count();

            $BRate = round(intval($BCount) / intval($allCount) *100);//中评率

            $CRate = 100 - $ARate - $BRate;//差评率
            $CCount = $allCount - $ACount - $BCount;

        }

        Yii::$app->redis_comments->set('fb_rate_A_' . $goods_id, $ARate);//好评率
        Yii::$app->redis_comments->set('fb_rate_B_' . $goods_id, $BRate);//中评率
        Yii::$app->redis_comments->set('fb_rate_C_' . $goods_id, $CRate);//差评率

        Yii::$app->redis_comments->set('fb_num_A_' . $goods_id, $ACount);//好评数
        Yii::$app->redis_comments->set('fb_num_B_' . $goods_id, $BCount);//中评数
        Yii::$app->redis_comments->set('fb_num_C_' . $goods_id, $CCount);//差评数
        Yii::$app->redis_comments->set('fb_num_' . $goods_id, $allCount);//评论总数

    }

    /*计算个人中心评论条数，并保存至redis*/
    public function updateUserCommentNumberToRedis($bestry_uid){

        $number['all'] = CommentsRelation::find()->where(['bestry_uid'=>$bestry_uid])->count();
        $number['perfect'] = CommentsRelation::find()->where(['bestry_uid'=>$bestry_uid, 'status'=>1])->count();//精华评论条数
        $number['reply'] = CommentsRelation::find()->where(['bestry_uid'=>$bestry_uid, 'is_reply'=>1])->count();//客服回复评论条数

        //Yii::$app->redis_comments->hmset('user_comment_number_' . $bestry_uid, $number);

        Yii::$app->redis_comments->set('u_comment_num_' . $bestry_uid, $number['all']);
        Yii::$app->redis_comments->set('u_comment_num_p_' . $bestry_uid, $number['perfect']);
        Yii::$app->redis_comments->set('u_comment_num_r_' . $bestry_uid, $number['reply']);
    }


    public static function addScore($old_status, $status, $bestry_uid){

        if($old_status != 2 && $status == 1){//精华 加试豆300
            MemberScore::addScore(300, '被评为精华评论', $bestry_uid, 5);
        }
        elseif($old_status != 1 && $status == 2){//审核不通过 减试豆100
            MemberScore::addScore(-100, '评论未通过,扣除试豆', $bestry_uid, 5);
        }
        elseif($old_status == 1 && $status == 2){//精华-》未通过 减试豆400
            MemberScore::addScore(-400, '精华评论改审核未通过', $bestry_uid, 5);
        }
        elseif($old_status == 2 && $status == 1){//未通过-》精华 加试豆400
            MemberScore::addScore(400, '审核未通过改精华评论', $bestry_uid, 5);
        }
    }

}
